﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Diagnostics;
using System.Drawing.Imaging;
using AudioCore.Common;

namespace AudioBookWS
{
    public partial class Resize : System.Web.UI.Page
    {
        private const string IdKey = "id";
        private const string AutKey = "aut";
        private const string Md5Key = "MD5_KEY";
        private const string ImageWidthKey = "w";
        private const string ImageHeightKey = "h";
        private const string IncrementKey = "inc";
        private const string ImageUrlKey = "u";
        private const string PrefixUrl = "&u=";
        private const string CropKey = "c";
        private const string QualityKey = "q";
        private const string RootImageFolderKey = "IMAGE_ROOT_FOLDER";
        private const string UsingImageCacheKey = "IMAGE_CACHE_USING";
        private const string Separator = @"\";
        private static readonly Size SizeDownload = new Size(128, 128);

        protected static TraceLog _ts = new TraceLog(Constant.TraceSourceName.General, SourceLevels.All);

        protected void Page_Load(object sender, EventArgs e)
        {
            //_ts.TraceDebug("Page_Load :: BEGIN");

            string imageID = Request.Params.Get(IdKey);
            string aut = Request.Params.Get(AutKey);
            string width = Request.Params.Get(ImageWidthKey);
            string height = Request.Params.Get(ImageHeightKey);
            string inc = Request.Params.Get(IncrementKey);
            string crop = Request.Params.Get(CropKey);
            string q = Request.Params.Get(QualityKey);
            int w = 0, h = 0, id = 0, ic = 0;
            int crp = 1; // 0: don't crop, 1: crop
            int quality;

            Int32.TryParse(width, out w);
            Int32.TryParse(height, out h);
            if (!Int32.TryParse(crop, out crp))
            {
                // Neu khong insert tham so crop (de trong) hoac insert sai format
                // thi set gia tri mac dinh co crp = 1 (nghia la co crop)
                crp = 1;
            }

            if (!Int32.TryParse(inc, out ic))
            {
                ic = 0;
            }

            if (!Int32.TryParse(q, out quality))
            {
                quality = 80;   // Default value
            }

            if (w > 0 && h == 0) h = w;
            if (h > 0 && w == 0) w = h;

            // Check url is exist on request string
            string url = Request.Params.Get(ImageUrlKey);
            string request = Request.RawUrl;
            request = request.Substring(request.IndexOf('?') + 1);

            int usingCache = 0;
            AppConfigUtils.GetInt(UsingImageCacheKey, ref usingCache);

            int indexUrl = Request.RawUrl.IndexOf(PrefixUrl);
            if (indexUrl > 0)
            {
                url = Request.RawUrl.Substring(indexUrl + PrefixUrl.Length);
            }

            if (!string.IsNullOrEmpty(url))
            {
                WriteImage(url, crp, w, h, quality);
            }

            // TODO : test
            Response.DisableKernelCache();

            //_ts.TraceDebug("Page_Load :: END");
        }

        private void WriteError()
        {
            Response.Write("Url khong chinh xac");
            Response.Flush();
            Response.Close();
        }

        private void WriteImage(System.Drawing.Image img)
        {
            //_ts.TraceDebug("WriteImage :: BEGIN");

            if (img == null)
            {
                WriteError();
                return;
            }

            Response.Buffer = true;

            Response.ContentType = "image/jpeg";
            Response.Clear();

            // Buffer response so that page is sent after processing is complete.
            Response.BufferOutput = true;

            try
            {
                // Write image to response object
                img.Save(Response.OutputStream, ImageFormat.Jpeg); // Why do you return Jpeg format only?
            }
            catch (Exception ex)
            {
                img.Save(Response.OutputStream, ImageFormat.Jpeg); // Why do you return Jpeg format only?
            }
            Response.OutputStream.Flush();
            Response.Flush();
            //_ts.TraceDebug("WriteImage :: END");
        }

        private void WriteImage(System.Drawing.Image img, int quality)
        {
            //_ts.TraceDebug("WriteImage :: BEGIN");

            if (img == null)
            {
                WriteError();
                return;
            }

            Response.Buffer = true;

            Response.ContentType = "image/jpeg";
            Response.Clear();

            // Buffer response so that page is sent after processing is complete.
            Response.BufferOutput = true;

            try
            {
                // Write image to response object
                //img.Save(Response.OutputStream, ImageFormat.Jpeg); // Why do you return Jpeg format only?

                if (quality > 0 && quality <= 100)
                    ImageUtils.SaveJpeg(Response.OutputStream, img, quality);
                else
                    img.Save(Response.OutputStream, ImageFormat.Jpeg); // Why do you return Jpeg format only?    

            }
            catch (Exception ex)
            {
                img.Save(Response.OutputStream, ImageFormat.Jpeg); // Why do you return Jpeg format only?
            }
            Response.OutputStream.Flush();
            Response.Flush();
            //_ts.TraceDebug("WriteImage :: END");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="crop">0: don't crop, other: crop</param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        private void WriteImage(string url, int crop, int w, int h, int quality)
        {
            //_ts.TraceDebug(string.Format("WriteImage :: URL={0}, CROP={1}, W={2}, H={3}", url, crop, w, h));

            bool cropImage = crop != 0 ? true : false;

            System.Drawing.Image imgOriginal = ImageUtils.DownloadImage(url);
            if (imgOriginal == null)
            {
                WriteError();
                return;
            }
            else if (w == 0 || h == 0)
            {
                WriteImage(imgOriginal, quality);
            }
            else
            {
                System.Drawing.Image imgResult = null;
                if (cropImage)
                {
                    imgResult = ImageUtils.ResizeImage(imgOriginal, new Size(w, h));
                }
                else
                {
                    imgResult = ImageUtils.Resize(imgOriginal, new Size(w, h));
                }
                WriteImage(imgResult, quality);

                imgOriginal.Dispose();
            }
        }

    }
}
